
import queue
import threading
import time


def plc_write16(t, x):
    return 1

def plc_get16(t):
    return 1

def plc_set16(t, x):
    return 1

def get_cam_ready(camid):
    return 1


def plc_out(isok0, isok1, pos):
    return 0


def plc_get_code():
    return 0


def plc_out_pos(pos):
    # 检测结果
    print(f'plc_out_pos {pos}')


def plc_out_ng(isok0, isok1):
    # 检测结果
    PLC_OK = ["D1020", "D1022"]
    print(f'plc_out_ng {isok0} {isok1}')


def plc_work_thd(ss):
    print("进入工作状态")
    # 告知PLC CAM处于READY状态可以接受数据
    while ss.running:
        ss.flag = 1
        ss.qq.put(1)
        for i in range(10):
            ss.code = i*100
            time.sleep(0.1)
        if not ss.running:
            break
        #ss.qq.put(0)
        ss.flag = 0
        time.sleep(1)
    pass


# 定时不断发送心跳信号，告知PLC


class PlcSL:
    def __init__(self) -> None:
        self.obj_is_in = False
        self.code = 0
        self.qq = queue.Queue()
        self.thread_work = None
        self.flag = 0
        self.con()

    def con(self):
        self.start()

    def __del__(self):
        self.stop()

    def start(self, qq=None):
        if self.thread_work is None:
            self.running = True
            self.thread_work = threading.Thread(
                target=plc_work_thd, args=(self,))
            self.thread_work.start()

    def set_pos(self, pos):
        pass

    def stop(self):
        if self.thread_work is not None:
            self.running = False
            self.thread_work.join()
            self.thread_work = None
            self.qq.put(None)

    def close(self):
        self.stop()
        pass


def test_myplc():
    plc = PlcSL()
    plc.start()
    for i in range(10):
        x = plc.qq.get()
        print('plc', x, plc.flag)
    plc.stop()
    print('asdf')


if __name__ == '__main__':
    test_myplc()
    pass
